import { Component } from '@angular/core';
import {
  ModalController,
  Events,
  Platform
} from '@ionic/angular';

import { QRScanner, QRScannerStatus } from '@ionic-native/qr-scanner/ngx';
import { Vibration } from '@ionic-native/vibration/ngx';
import { ViewController } from '@ionic/core';
import { InAppBrowser } from '@ionic-native/in-app-browser/ngx';


@Component({
  selector: 'modal-qr-scanner',
  templateUrl: 'qr-scanner.html',
  styleUrls: ['./qr-scanner.scss'],
  providers: [Vibration],
})
export class QRScannerModal {
  constructor(
    private events: Events,
    private qrScanner: QRScanner,
    private vibration: Vibration,
    private modelCtrl: ModalController,
    private platform: Platform,
    private iab: InAppBrowser
  ) {
    this.platform.backButton.subscribe(res => {
      this.dismiss();
    })
    this.scanQrCode();
  }
  private ionOutlet: HTMLElement = document.getElementsByTagName('ion-router-outlet')[0];
  private scanQrCode(): void {
    this.qrScanner
      .prepare()
      .then((status: QRScannerStatus) => {
        if (status.authorized) {
          const scanSub = this.qrScanner.scan().subscribe((qrCode: string) => {
            this.vibration.vibrate(30);
            let response;
            try {
              response = JSON.parse(qrCode);
            } catch (e) {
              response = qrCode;
            }

            this.hideCamera();
            scanSub.unsubscribe();
            this.dismiss(response);
            if (response.indexOf('http') !== -1) {
              console.log('是链接', response);
              const pageView = this.iab.create(response + '&&userAgent=efos');
              console.log('打开链接', pageView);
              pageView.show();
            } else {
              console.log('非链接');
            }
          });

          this.ionOutlet.classList.add('transparent');
          this.showCamera();
        } else if (status.denied) {
          console.error('QR_CODE.PERMISSION_PERMANENTLY_DENIED');
          this.dismiss();
        } else {
          console.error('QR_CODE.PERMISSION_DENIED');
          this.dismiss();
        }
      })
      .catch((e: any) => {
        console.error('QR_CODE.PROBLEM_TEXT');
        this.dismiss();
      });
  }

  private showCamera() {
    this.qrScanner.show();
    this.events.publish('qrScanner:show');
  }

  public hideCamera() {
    this.qrScanner.hide();
    this.events.publish('qrScanner:hide');
  }

  public dismiss = (qrCode: object = null) => {
    this.qrScanner.getStatus().then((status: QRScannerStatus) => {
      if (status.showing) {
        this.hideCamera();
      }
    });
    this.ionOutlet.classList.remove('transparent');
    this.modelCtrl.dismiss(qrCode);
  }

  ionViewDidLeave() {
    this.hideCamera();
    this.qrScanner.destroy();
  }
}
